<template>
  <div>
    <h3>权限管理组件</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon> </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader v-model="cateId" :options="cateList" :props="cascaderProps" @change="selectCate" clearable></el-cascader>
        </el-col>
        <el-col></el-col>
      </el-row>

      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 动态参数页面 -->
          <el-button size="mini" type="primary" :disabled="isButtonDisabled" @click="addData">添加参数</el-button>
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag type="success" :key="i" v-for="(tag, i) in scope.row.attr_vals" closable @close="valClose(scope.row, i)">
                  {{ tag }}
                </el-tag>
                <el-input
                  class="tagInput"
                  v-if="scope.row.inputVisible"
                  size="small"
                  v-el-focus
                  v-model.trim="scope.row.inputText"
                  @keyup.enter.native="doAddTag(scope.row)"
                  @blur="scope.row.inputVisible = false"
                >
                </el-input>
                <el-tag v-else @click="scope.row.inputVisible = true" class="btnAdd">+ New Tag</el-tag>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEdit(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="showDelete(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 静态属性页面 -->
          <el-button size="mini" type="primary" :disabled="isButtonDisabled" @click="addData">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(tag, i) in scope.row.attr_vals" closable @close="valClose(scope.row, i)">
                  {{ tag }}
                </el-tag>
                <el-input
                  class="tagInput"
                  v-if="scope.row.inputVisible"
                  size="small"
                  v-el-focus
                  v-model.trim="scope.row.inputText"
                  @keyup.enter.native="doAddTag(scope.row)"
                  @blur="scope.row.inputVisible = false"
                >
                </el-input>
                <el-tag v-else @click="scope.row.inputVisible = true" class="btnAdd">+ New Tag</el-tag>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEdit(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="showDelete(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 修改参数或属性对话框 -->
      <el-dialog :title="'修改' + this.titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <!-- 添加表单 -->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加参数或属性对话框 -->
      <el-dialog :title="'添加' + this.titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
        <!-- 添加表单 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'params',
  data() {
    return {
      // 分类ID
      cateId: [],
      //   分类数据
      cateList: [],
      //   分类配置
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        // 是否可以选择tree主干
        checkStrictly: false
      },
      // 被激活的页签的名称
      activeName: 'many',
      //   动态参数数据
      manyTableData: [],
      //   静态参数数据
      onlyTableData: [],
      //   是否显示新增弹出层
      addDialogVisible: false,
      //   是否显示修改弹出层
      editDialogVisible: false,
      //   弹出层表单
      addForm: {
        attr_name: ''
      },
      //   弹出层表单
      editForm: {
        attr_name: '',
        attrId: 0
      },
      //   验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      editFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    //   选中分类事件
    selectCate() {
      // 判断是否为3级分类
      if (this.cateId.length !== 3) {
        this.cateId = []
        this.manyTableData = []
        this.onlyTableData = []
        return this.$messagebox.alert('请选择第【3】级分类!!!!', '敲NM')
      }
      this.getParamsData()
    },
    //    查询分类数据 获取整体下拉框分类数据
    async getCateList() {
      const { data: res } = await this.$axios({
        url: 'categories',
        method: 'GET'
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 切换页签处理函数
    handleClick() {
      this.getParamsData()
    },
    // 获取分类数据的属性与值
    async getParamsData() {
      // 选中三级分类发起请求
      const { data: res } = await this.$axios.get(`categories/${this.compuCateId}/attributes`, { params: { sel: this.activeName } })
      //   判断当前为参数或属性--进行对应的赋值
      if (res.data) {
        res.data.forEach((e) => {
          // 拆分标签为数组
          e.attr_vals = e.attr_vals ? e.attr_vals.split(' ') : []
          e.inputVisible = false
          e.inputText = ''
        })
      }
      this.activeName === 'many' ? (this.manyTableData = res.data) : (this.onlyTableData = res.data)
    },
    // 添加属性值
    async doAddTag(val) {
      val.inputVisible = false
      if (val.inputText === '') return
      // 将文本框的值加入数据渲染
      val.attr_vals.push(val.inputText)
      const { data: res } = await this.$axios.put(`categories/${this.compuCateId}/attributes/${val.attr_id}`, {
        attr_sel: val.attr_sel,
        attr_name: val.attr_name,
        attr_vals: val.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('添加失败')
      this.$message.success('添加成功')
      val.inputText = ''
    },
    // 添加属性
    addData() {
      this.addDialogVisible = true
    },
    // 删除属性
    async valClose(val, index) {
      val.attr_vals.splice(index, 1)
      const { data: res } = await this.$axios.put(`categories/${this.compuCateId}/attributes/${val.attr_id}`, {
        attr_sel: val.attr_sel,
        attr_name: val.attr_name,
        attr_vals: val.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
    },
    // 关闭新增弹出层
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定新增参数
    addParams() {
      this.$refs.addFormRef.validate(async (val) => {
        if (!val) return this.$message.error('请输入完整')
        const { data: res } = await this.$axios.post(`categories/${this.compuCateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.addDialogVisible = false
        this.getParamsData()
        this.$message.success(res.meta.msg)
      })
    },
    // 点击编辑
    async showEdit(id) {
      // 可直接从表格项拿，不需要发请求
      const { data: res } = await this.$axios.get(`categories/${this.compuCateId}/attributes/${id}`, { attr_sel: this.activeName })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm.attr_name = res.data.attr_name
      this.editForm.attrId = id
      this.editDialogVisible = true
    },
    // 取消修改表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定
    async editParams() {
      const { data: res } = await this.$axios.put(`categories/${this.compuCateId}/attributes/${this.editForm.attrId}`, { attr_sel: this.activeName, attr_name: this.editForm.attr_name })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsData()
      this.editDialogVisible = false
    },
    // 删除参数
    async showDelete(id) {
      try {
        await this.$messagebox.confirm('是否删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 点击确定做的事情
        const { data: res } = await this.$axios.delete(`categories/${this.compuCateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsData()
      } catch (error) {
        //   点击取消做的事情
        this.$message.info('取消删除')
      }
    }
  },
  created() {
    //   开局一条狗(拿到下拉框数据)
    this.getCateList()
  },
  //   计算属性
  computed: {
    //   是否启用状态 需要被禁用返回true,否则false
    isButtonDisabled() {
      return this.cateId.length !== 3
    },
    // 当前选中的三级分类的ID
    compuCateId() {
      if (this.cateId.length === 3) {
        return this.cateId[this.cateId.length - 1]
      }
      return null
    },
    // 判断类型返回名字
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>

<style scoped>
.cat_opt {
  margin: 15px;
}
.el-tag {
  margin: 0 5px;
}
.tagInput {
  width: 100px;
}
.btnAdd {
  cursor: pointer;
}
</style>
